package com.ojoin.trade.common.utils;

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.util.Enumeration;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {
	
	private static final Pattern IP_PATTERN = Pattern.compile("\\d{1,3}(\\.\\d{1,3}){3,5}$");
	
    private IpUtils() {
    }

    public static String getLocalIp(){
    	return getLocalAddress0().getHostAddress();
    }
    private static InetAddress getLocalAddress0() {
		InetAddress localAddress = null;
		try {
			localAddress = InetAddress.getLocalHost();
			if (isValidAddress(localAddress))
				return localAddress;
		} catch (Throwable e) {
		}
		try {
			Enumeration interfaces = NetworkInterface.getNetworkInterfaces();
			while ((interfaces != null) && (interfaces.hasMoreElements()))
				try {
					NetworkInterface network = (NetworkInterface) interfaces.nextElement();
					Enumeration addresses = network.getInetAddresses();
					while ((addresses != null) && (addresses.hasMoreElements()))
						try {
							InetAddress address = (InetAddress) addresses.nextElement();
							if (isValidAddress(address))
								return address;
						} catch (Throwable e) {
						}
				} catch (Throwable e) {
				}
		} catch (Throwable e) {
		}
		return localAddress;
	}
    
    private static boolean isValidAddress(InetAddress address) {
		if ((address == null) || (address.isLoopbackAddress()))
			return false;
		String name = address.getHostAddress();
		return ((name != null) && (!("0.0.0.0".equals(name))) && (!("127.0.0.1".equals(name)))
				&& (IP_PATTERN.matcher(name).matches()));
	}
    
    public static String getIpAddr(HttpServletRequest request) {
        if (request == null) {
            return "unknown";
        }
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Forwarded-For");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("X-Real-IP");
        }

        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }
}
